// src\components\publish-manage\usePublish.js
// 用于集合一些对NewsPublish组件进行数据操作的方法

import { notification } from "antd";
import axios from "axios";
import { useEffect, useState } from "react";

function usePublish(type) {
    //获取当前的用户登录信息
    const { username } = JSON.parse(localStorage.getItem('token'));
    const [dataSource, setdataSource] = useState([]);
    //后端获取相应的数据
    useEffect(() => {
        axios.get(`http://localhost:8888/news?author=${username}&publishState=${type}&_expand=category`).then(res => {
            setdataSource(res.data);
        })
    }, [username, type]);
    // 将待发布的新闻进行发布操作
    const handlePublish = (id) => {
        setdataSource(dataSource.fill(item => item.id !== id));
        axios.patch(`http://localhost:8888/news/${id}`, {
            'publishState': 2,//将新闻发布状态改为2==发布
            'publishTime': Date.now()
        }).then(res => {
            notification.info({
                messgae: '通知',
                description: `您可以到【发布管理/已经发布】中查看您的新闻`,
                placement: 'bottomRight'
            });
        })
    }
    // 将已发布的新闻变为已下线状态
    const handleSunset = (id) => {
        setdataSource(dataSource.filter(item => item.id !== id));
        axios.patch(`http://localhost:8888/news/${id}`, {
            'publishState': 3,//状态码改为“已下线”
        }).then(res => {
            notification.info({
                message: `通知`,
                description:
                    `您可以到【发布管理/已下线】中查看您的新闻`,
                placement: "bottomRight"
            })
        })
    }
    // 将“已下线”的新闻删除
    const handleDelete = (id) => {
        setdataSource(dataSource.filter(item => item.id !== id))
        axios.delete(`http://localhost:8888/news/${id}`).then(res => {
            notification.info({
                message: `通知`,
                description:
                    `您已经删除了已下线的新闻`,
                placement: "bottomRight"
            });
        })

    }
    return {
        dataSource,
        handlePublish,
        handleSunset,
        handleDelete
    }

}

export default usePublish